import {Content, Events, IonicPage, NavController, ToastController} from "ionic-angular";
import {Component, QueryList, ViewChild, ViewChildren} from "@angular/core";
import {
    ActivityFilterModel, ActivityStatus
} from "../../../model/pages/activity/activity-filter/activity-filter.model";
import {ActivityListProvider} from "../../../providers/activity/activity-list/activity-list.provider";
import {ActivityListItemModel} from "../../../model/pages/activity/activity-list/activity-list-item.model";
import {ActivitDetailPage} from "../acitivity-detail/activit-detail/activit-detail";
import {PageParamsModel} from "../../../model/common/page-params.model";
import * as _ from 'lodash';
import {AdpLazyloadComponent} from "../../../components/common/adp-lazyload/adp-lazyload.component";
import {LoadingService} from "../../../services/common/loading.service";
import {FileService} from "../../../services/native/file/file.service";
import {LocalStorageService} from "../../../services/native/local-storage/local-storage.service";
import {File} from "@ionic-native/file";
import {FileTransfer} from "@ionic-native/file-transfer";
import {AuthService} from "../../../services/common/auth.service";
import {CacheImgService} from "../../../services/native/cache-img/cache-img.service";

@IonicPage()
@Component({
    selector: 'activity-list',
    templateUrl: 'activity-list.html',
    providers: [
        ActivityListProvider,
        LoadingService,
        FileService,
        LocalStorageService,
        File,
        FileTransfer,
        AuthService
    ]
})
export class ActivityListPage {
    @ViewChildren(AdpLazyloadComponent) lazyImgs: QueryList<AdpLazyloadComponent>;
    @ViewChild(Content) content: Content;

    /**
     * 筛选条件
     * @type {ActivityFilterModel}
     */
    private filter: ActivityFilterModel = new ActivityFilterModel();

    /**
     * 附加筛选条件变量（用作展示）
     */
    private tempFilter: ActivityFilterModel = {
        classify: 0,
        type: [],
        status: [],
        startTime: null,
        endTime: null
    };

    /**
     * 活动列表
     * @type {ActivityListItemModel[]}
     */
    private activityList: ActivityListItemModel[] = [];

    //懒加载img类名
    private imgClassName = 'msl-card-img';
    //预览活动列表
    private previewList: Array<any> = [];
    //当前试图，0代表市场活动，1代表增员活动
    private currentView: number = 0;
    //所有的类型
    private allTypes;
    //是否加载完毕
    private isLoaded = false;
    private azureInfo;
    private showRoster;
    private taskList = [];

    constructor(private navCtrl: NavController,
                private events: Events,
                private activityListPro: ActivityListProvider,
                private load: LoadingService,
                private toast: ToastController,
                private fileService: FileService,
                private authService: AuthService,
                private cacheService: CacheImgService) {
        this.filter.status = [ActivityStatus.notStart, ActivityStatus.processing, ActivityStatus.over];
    }

    /**
     * 首次进入获取数据、订阅条件筛选
     */
    ionViewDidLoad() {
        this.receiveFilterEvent();
        this.getAzureInfo();
        this.showRoster = this.authService.showRoster();
    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     */
    toastCtrl(message: string) {
        this.toast.create({
            message: message,
            position: 'middle',
            duration: 1200
        }).present();
    }

    /**
     * 取消订阅条件筛选
     */
    ionViewWillUnload() {
        this.events.unsubscribe('activity:search');
    }

    ionViewWillLeave() {
        // this.resetFilter();
    }

    resetFilter() {
        this.filter = new ActivityFilterModel();
        this.filter.status = [ActivityStatus.notStart, ActivityStatus.processing, ActivityStatus.over];
        this.tempFilter = {
            classify: 0,
            type: [],
            status: [],
            startTime: null,
            endTime: null
        };
    }

    getAzureInfo() {
        this.isLoaded = false;
        this.load.showLoading();
        this.fileService.getAzureInfo().subscribe((data) => {
            this.azureInfo = data.azureInfo;
            this.getActivityType();
        }, err => {
            console.log(err);
            this.getActivityType();
        });
    }

    /**
     * 切换当前试图
     */
    switchCurrentView(num) {
        this.currentView = num;
        this.tempFilter.classify = num;
        this.filter.classify = num;
        this.resetFilter();
        this.getActivityType(null, true);
    }

    /**
     * 获取预览活动列表
     * @param {any} refresher
     */
    getPreviewList(refresher = null) {
        this.taskList = [];
        this.activityListPro.getPreviewList(this.currentView, 1)
            .subscribe((res: Array<any>) => {
                // res.forEach((el) => {
                    // el.bannerUrl = this.fileService.getCompletePath(el.bannerUrl, this.azureInfo);
                    // this.cacheService.getImgPath(el.bannerUrl, this.azureInfo)
                    //     .then((path) => {
                    //     el.bannerUrl = path;
                    // });
                // });
                this.previewList = res;
                this.getNextPageData(refresher);
            }, err => {
                this.getNextPageData(refresher);
                if (refresher) {
                    refresher.complete();
                }
                this.load.dismissLoading();
            });
    }

    /**
     * 加载活动列表
     */
    getNextPageData(refresher = null, needLoading = false) {
        if (needLoading) {
            this.load.showLoading();
        }
        this.activityListPro.getActivityList(this.filter)
            .subscribe((res: ActivityListItemModel[]) => {
                // res.forEach((el) => {
                    // el.bannerUrl = this.fileService.getCompletePath(el.bannerUrl, this.azureInfo);
                    // this.cacheService.getImgPath(el.bannerUrl, this.azureInfo)
                    //     .then((path) => {
                    //         el.bannerUrl = path;
                    //         setTimeout(() => {
                    //             this.lazyLoad();
                    //         }, 0);
                    //     });
                // });
                this.activityList = res;
                setTimeout(() => {
                    this.lazyLoad();
                }, 0);
                if (refresher) {
                    refresher.complete();
                }
                this.isLoaded = true;
                this.load.dismissLoading();
            }, () => {
                this.isLoaded = true;
                if (refresher) {
                    refresher.complete();
                }
                this.load.dismissLoading();
            });
    }

    /**
     * 获取活动类型
     */
    getActivityType(refresher = null, needLoading = false) {
        this.isLoaded = false;
        if (needLoading) {
            this.load.showLoading();
        }
        this.activityListPro.getActivityType(this.currentView, 1)
            .subscribe((res: Array<any>) => {
                this.allTypes = res;
                this.filter.type = this.allTypes.map((item) => {
                    return item.id;
                });
                this.getPreviewList(refresher);
            }, err => {
                this.isLoaded = true;
                if (refresher) {
                    refresher.complete();
                }
                this.load.dismissLoading();
            });
    }

    /**
     * 接收筛选条件
     */
    receiveFilterEvent() {
        this.events.subscribe('activity:search',
            (filter: ActivityFilterModel, pageParams: PageParamsModel) => {
                this.tempFilter = filter;

                let cloneFilter = _.cloneDeep(filter);
                if (cloneFilter.type.length === 0) {
                    cloneFilter.type = this.allTypes.map((item) => {
                        return item.id;
                    });
                }
                if (cloneFilter.status.length === 0) {
                    cloneFilter.status = [ActivityStatus.notStart, ActivityStatus.processing, ActivityStatus.over];
                }
                this.filter = cloneFilter;
                this.taskList = [];
                this.getNextPageData(null, true);
            });
    }

    computeType(val) {
        let typeName = '';
        this.allTypes.forEach((item) => {
            if (Number(item.id) === val) {
                typeName = item.name;
            }
        });
        return typeName;
    }

    lazyLoad() {
        _.throttle(() => {
            this.lazyImgs['_results'].forEach((item) => {
                // item.compute();
                if (item.needLoading() && this.taskList.indexOf(item.lazysrc) === -1) {
                    // console.log(item.lazysrc);
                    this.taskList.push(item.lazysrc);
                    item.cacheImg(this.cacheService.getImgPath(item.lazysrc, this.azureInfo));
                }
            });
        }, 50)();
    }

    /**
     * 跳转到活动详情页
     * @param {ActivityListItemModel} activity
     */
    toActivityDetail(activity: ActivityListItemModel) {
        this.navCtrl.push('ActivitDetailPage', {
            id: activity.id,
            classify: this.currentView
        });
    }

    toRosterList() {
        this.navCtrl.push('RosterListPage', null, {
            animate: false
        });
    }

    toFilterPage() {
        this.navCtrl.push('ActivityFilterPage', {
            classify: this.currentView,
            allTypes: this.allTypes,
            filter: _.cloneDeep(this.tempFilter)
        });
    }

}
